<?php

namespace app\adminapi\controller;

use app\common\model\User;
use Firebase\JWT\BeforeValidException;
use Firebase\JWT\ExpiredException;
use Firebase\JWT\JWT;
use Firebase\JWT\SignatureInvalidException;
use think\admin\helper\ValidateHelper;
use think\App;
use think\Exception;
use think\facade\Db;
use think\facade\Request;

class Common
{
    public $user_id;
    public $role_id;
    public $controller_action;

    public function __construct()
    {
        $this->auth();


        $model_name = strtolower(app('http')->getName());
        $controller_name = strtolower(request()->controller());
        $action_name = strtolower(request()->action());
        $this->controller_action = $model_name.'@'.$controller_name.'@'.$action_name;

        //1表示系统超级管理员，不需要判断权限节点
        if($this->role_id !== 1) {
            $this->checkRoleRight();
        }
    }

    /**
     * 验证用户权限
     */
    protected function auth()
    {
        $token = request()->header('token');

        if(empty($token)){
            echo json_encode(['code'=>-1,'msg'=>'请先登录']);
            exit();
        }

        try {
            JWT::$leeway = 60;//当前时间减去60，把时间留点余地
            $decoded = JWT::decode($token,"pms",['HS256']);
            $decoded = $decoded->data;

            $res = Db::name('system_user')->where('id',$decoded->user_id)->find();
            if (!$res) {
                echo json_encode(['code'=>0,'msg'=>'用户不存在']);
                exit();
            }

            $this->user_id = $res['id'];
            $this->role_id = $res['role_id'];


        } catch (SignatureInvalidException $e) {
            echo json_encode(['code'=>-1,'msg'=>'签名不正确']);
            exit();
        } catch (BeforeValidException $e) {
            echo json_encode(['code'=>-1,'msg'=>'签名在某个时间点之后才能用']);
            exit();
        } catch (ExpiredException $e) {
            echo json_encode(['code'=>-1,'msg'=>'签名已过期']);
            exit();
        } catch (\Exception $e) {
            echo json_encode(['code'=>-1,'msg'=>'未知错误']);
            exit();
        }
    }

    /**
     * 权限判断
     */
    public function checkRoleRight()
    {   
        // 公共接口
        $common = ["merchants@user@getnum","merchants@user@resetpsd"];

        $rule_list = Db::name('role')->where('id',$this->role_id)->value('rule_list');

        $merchant_menu = Db::name('menu')->where('id','in',$rule_list)->where('type',2)->field('id,title,url')->select()->toArray();

        // 授权
        $rule = '';
        foreach ($merchant_menu as $key => $value) {
            $rule .= $value['url'].',';
        }
        $rule = array_unique(array_filter(explode(",",$rule)));

        if ($rule) {
            $rule = array_merge($rule,$common);
        }

        if(!in_array($this->controller_action,$rule)){
            throw new Exception("没有操作权限");
        }

    }

    /**
     * 快捷输入并验证（ 支持 规则 # 别名 ）
     * @param array $rules 验证规则（ 验证信息数组 ）
     * @param string|array $type 输入方式 ( post. 或 get. )
     * @param callable|null $callable 异常处理操作
     * @return array
     */
    protected function _vali(array $rules, $type = '', ?callable $callable = null): array
    {
        return ValidateHelper::instance()->init($rules, $type, $callable);
    }
}